package dk.almbrand.microservice.circuitbreaker.states;

import dk.almbrand.microservice.circuitbreaker.CircuitBreaker;

import dk.almbrand.microservice.circuitbreaker.exceptions.OpenCircuitException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Timer;
import java.util.TimerTask;

public class Open extends CircuitBreakerState {
    Logger logger = LoggerFactory.getLogger(Open.class);

    public Open(CircuitBreaker circuitBreaker) {
        super(circuitBreaker);
        logger.info("open");
        new Timer().schedule(new MoveToHalfOpenStateTask(), (circuitBreaker.getTimeoutNanoSeconds() / 1000000));
    }

    @Override
    public void protectedCodeIsAboutToBeCalled() throws OpenCircuitException {
        super.protectedCodeHasBeenCalled();
        throw new OpenCircuitException();
    }

    class MoveToHalfOpenStateTask extends TimerTask {
        public void run() {
            logger.info("timeout");
            circuitBreaker.moveToHalfOpenState();
            circuitBreaker.prepareFailureCountForHalfOpen();            
            Thread.currentThread().stop();
        }
    }
}
